﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net 管理页面控制器        ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Wedn.Net.Common;
using Wedn.Net.Controller.Base;
using Wedn.Net.Model;
using Wedn.Net.Utility;

namespace Wedn.Net.Admin.Controllers
{
    /// <summary>
    /// 管理页面控制器
    /// </summary>
    public class AdminController : AdminBaseController
    {

        #region Dashboard

        #region 管理页面首页框架 +ActionResult Index()
        /// <summary>
        /// 管理页面首页框架
        /// </summary>
        public ActionResult Index()
        {
            ViewBag.Title = "仪表盘";
            return View();
        }
        #endregion

        #region 管理页面首页 +ActionResult Welcome()
        /// <summary>
        /// 管理页面首页
        /// </summary>
        public ActionResult Welcome()
        {
            ViewBag.Title = "仪表盘";
            return View();
        }
        #endregion

        #endregion

        #region Post

        #region 所有Post页面 +ActionResult Post(int page = 1, string type = "post")
        /// <summary>
        /// 所有Post页面
        /// </summary>
        /// <param name="type">Post类型</param>
        /// <param name="page">页码</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public ActionResult Post(string type = "post", int page = 1, int status = 0)
        {
            int pageSize = 20;
            PostType postType = PostType.Article;

            //取标签集合
            var terms = BllInstance.TermManager.Select(t => true).ToList();
            //关系信息实体集合
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (int)RelationObjectType.Post).ToList();
            ViewBag.Type = type;
            if (type == "page")
            {
                postType = PostType.Page;
                ViewBag.Title = "所有页面";
            }
            else
            {
                ViewBag.Title = "所有文章";
                //格式化类别信息
                IList<Term> formatCategorys = new List<Term>();
                BllInstance.TermManager.LoadTierCategoryList(terms.Where(c => c.Type == (int)TermType.PostCategory).ToList(), formatCategorys, "─", 0);
                ViewBag.FormatCategorys = formatCategorys;
            }
            //取主体信息数据集合
            int totalCount;
            IEnumerable<Post> posts;
            switch (status)
            {
                case -1://全部
                    posts = BllInstance.PostManager.SelectPage(page, pageSize, out totalCount,
                               p =>
                               p.Type == (int)postType,//(int)PostStatus.Pubilc,
                               p => p.Modified, true
                               ).ToList();
                    break;
                case 1://草稿
                    posts = BllInstance.PostManager.SelectPage(page, pageSize, out totalCount,
                               p =>
                               p.Type == (int)postType &&
                               p.Status == (int)PostStatus.Draft,
                               p => p.Modified, true
                               ).ToList();
                    break;
                case 2://回收站
                    posts = BllInstance.PostManager.SelectPage(page, pageSize, out totalCount,
                               p =>
                               p.Type == (int)postType &&
                               p.Status == (int)PostStatus.Recycle,
                               p => p.Modified, true
                               ).ToList();
                    break;
                case 0://已发布
                default:
                    posts = BllInstance.PostManager.SelectPage(page, pageSize, out totalCount,
                               p =>
                               p.Type == (int)postType &&
                               p.Status == (int)PostStatus.Pubilc,
                               p => p.Modified, true
                               ).ToList();
                    break;
            }

            foreach (var item in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == item.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id));
                item.Link = Url.Action("Detail", "Blog", new { item = item.Slug });
                //item.Author = users.FirstOrDefault(u => u.Id == item.UserId).NickName;
                //item.Categorys = string.Join("、", itemTerms.Where(c => c.Type == (short)TermType.PostCategory).Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", Url.Action("Category", "Blog", new { item = !string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name }), c.Name)));
                //item.Tags = string.Join("、", itemTerms.Where(c => c.Type == (short)TermType.PostTag).Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", Url.Action("Category", "Blog", new { item = !string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name }), c.Name)));
            }
            //往视图包存放数据
            ViewBag.PostType = postType;
            ViewBag.Status = status;
            ViewBag.Terms = terms;
            ViewBag.Relations = relations;
            ViewBag.TotalCount = totalCount;
            ViewBag.TotalPage = Math.Ceiling(ViewBag.TotalCount / (double)pageSize);
            ViewBag.PageIndex = page;
            return View(posts);
        }
        #endregion

        #region 发表Post页面 +ActionResult Writer(int item = 0, string type = "post")
        /// <summary>
        /// 发表Post页面
        /// </summary>
        /// <param name="item">编辑项</param>
        /// <param name="type">Post类型</param>
        /// <returns></returns>
        public ActionResult Writer(int item = 0, string type = "post")
        {
            Post post;
            if (item == 0)
            {
                ViewBag.Title = "撰写新";
                post = new Post
                {
                    Type = type == "post" ? (short)PostType.Article : (short)PostType.Page,
                    PubDate = DateTime.Now,
                    Modified = DateTime.Now
                };
            }
            else
            {
                ViewBag.Title = "编辑";
                post = BllInstance.PostManager.SelectSingle(p => p.Id == item);
            }
            ViewBag.Title += type == "post" ? "文章" : "页面";
            ViewBag.Type = type;
            IList<Term> terms = BllInstance.TermManager.Select(c => true).ToList();
            IList<Term> categorys = terms.Where(c => c.Type == (int)TermType.PostCategory).ToList();
            IList<Term> tags = terms.Where(c => c.Type == (int)TermType.PostTag).ToList();
            IList<Term> formatCategorys = new List<Term>();
            BllInstance.TermManager.LoadTierCategoryList(categorys, formatCategorys, "--", 0);

            ViewBag.Relations = BllInstance.RelationManager.Select(r => r.ObjectId == item && r.ObjectType == (int)RelationObjectType.Post).ToList();
            ViewBag.Tags = tags;
            ViewBag.Categorys = formatCategorys;
            ViewBag.PopCategorys = categorys.OrderByDescending(c => c.Count).Take(10).ToList();
            ViewBag.Authors = BllInstance.UserManager.Select(u => u.Status == (int)UserStatus.Normal && u.Role > (int)UserRole.Subscriber).ToList();
            return View(post);
            //return View();
        }
        #endregion

        #endregion

        #region Term

        #region 标签管理页面 +ActionResult Term(string type = "post_category")
        /// <summary>
        /// 标签管理页面
        /// </summary>
        /// <param name="type">标签类型</param>
        /// <returns></returns>
        public ActionResult Term(string type = "post_category")
        {
            //权限校验
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));
            IList<Term> list = null;
            switch (type)
            {
                default:
                case "post_category":
                    ViewBag.Title = "分类目录";
                    ViewBag.Type = (int)TermType.PostCategory;
                    list = BllInstance.TermManager.Select(c => c.Type == (int)TermType.PostCategory).ToList();
                    IList<Term> postCategorys = new List<Term>();
                    BllInstance.TermManager.LoadTierCategoryList(list, postCategorys, "─", 0);
                    ViewBag.Terms = postCategorys;
                    break;
                case "post_tag":
                    ViewBag.Title = "标签";
                    ViewBag.Type = (int)TermType.PostTag;
                    list = BLLFactory.BLLFactory.Instance.TermManager.Select(c => c.Type == (int)TermType.PostTag).ToList();
                    ViewBag.Terms = list;
                    break;
                case "link_category":
                    ViewBag.Title = "链接分类目录";
                    ViewBag.Type = (int)TermType.LinkCategory;
                    list = BllInstance.TermManager.Select(c => c.Type == (int)TermType.LinkCategory).ToList();
                    IList<Term> linkCategorys = new List<Term>();
                    BllInstance.TermManager.LoadTierCategoryList(list, linkCategorys, "─", 0);
                    ViewBag.Terms = linkCategorys;
                    break;
            }
            return View();
        }
        #endregion

        #endregion

        #region Style

        #region 主题管理页面 +ActionResult Theme()
        /// <summary>
        /// 主题管理页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Theme()
        {
            //var theme = new Wedn.Net.Model.View.Theme()
            //{
            //    Name = "Default",
            //    Version = "1.0.0.0",
            //    Author = "iceStone",
            //    Email = "ice@wedn.net",
            //    Link = "http://blog.wedn.net",
            //    PubDate = DateTime.Now
            //};
            //var res=XmlHelper.XmlSerialize(theme);
            //return Content(res);
            var themeList = new List<Model.View.Theme>();
            Model.View.Theme currentTheme = null;
            var path = Server.MapPath(Config.ThemeRoot);
            var dir = new DirectoryInfo(path);
            if (!dir.Exists) ShowNotFoundPage();
            var themeDirs = dir.GetDirectories();
            foreach (var themeDir in themeDirs)
            {
                if (!themeDir.Exists) continue;
                var xmls = themeDir.GetFiles("theme.xml", SearchOption.TopDirectoryOnly);
                if (xmls.Length != 1) continue;
                var item = XmlHelper.XmlDeserializeFromFile<Model.View.Theme>(xmls[0].FullName, Encoding.UTF8);

                if (string.IsNullOrEmpty(item.ScreenShots))
                {
                    var temp = themeDir.GetFiles("screenshot.*", SearchOption.TopDirectoryOnly);
                    if (temp.Length == 1)
                        item.ScreenShots = Config.ThemeRoot + themeDir.Name + "/" + temp[0].Name;
                    else
                        item.ScreenShots = "/Content/Images/screenshot.png";
                }
                if (item.Name.ToLower() != Setting.Theme.ToLower())
                    themeList.Add(item);
                else
                    currentTheme = item;
            }
            ViewBag.Title = "管理主题";
            ViewBag.CurrentTheme = currentTheme;
            return View(themeList);
        }
        #endregion

        #region 启用主题 +RedirectResult ThemeActivate(string item)
        /// <summary>
        /// 启用主题
        /// </summary>
        /// <param name="item">启用项</param>
        /// <returns></returns>
        [HttpGet]
        public RedirectResult ThemeActivate(string item)
        {
            BllInstance.OptionManager.UpdateValue("theme", item);
            BllInstance.OptionManager.SaveChanges();
            TEngine.TemplateConfig.RegisterViewEngines();
            return Redirect(Url.Action("Theme"));
        } 
        #endregion

        #endregion

        #region Option

        #region 配置页面 +ActionResult Option(string go = "general")
        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Option(string go = "general")
        {
            //权限校验
            if (CurrentUser.Role < (short)UserRole.Writer) return Redirect(Url.Action("Index", "Login"));

            ViewBag.Anchor = go;
            switch (go)
            {
                case "general":
                    ViewBag.Title = "常规配置";
                    break;
                case "seo":
                    ViewBag.Title = "SEO配置";
                    break;
                case "write":
                    ViewBag.Title = "撰写配置";
                    break;
                case "read":
                    ViewBag.Title = "阅读配置";
                    break;
                case "discussion":
                    ViewBag.Title = "讨论配置";
                    break;
                case "media":
                    ViewBag.Title = "多媒体配置";
                    break;
                case "route":
                    ViewBag.Title = "路由配置";
                    ViewBag.RouteContent = System.IO.File.ReadAllText(Server.MapPath("/config/route.config"), Encoding.UTF8);
                    break;
                case "smtp":
                    ViewBag.Title = "SMTP配置";
                    break;
            }
            return View();
        }
        #endregion

        #endregion
    }
}